<template>
  <div class="menuPermission">
    <el-row>
      <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="roles mt20">
        <i class="lineJue" v-if="menus"></i>
        角色选择<i class="tipMessage">（<span class="tip">注意：</span>只能选择一个角色）</i>：
        <el-checkbox-group
          :min="1"
          :max="2"
          @change="changeRoles"
          v-model="roleInfo.perCode">
          <div v-for="(role, index) in roles" :key="index" class="mt20">
            <el-checkbox :label="role.code" :key="role.code">{{role.cName}}</el-checkbox>
          </div>
        </el-checkbox-group>
      </el-col>
      <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="menuTree mt20">
        <i class="lineJue" v-if="isShowMenu"></i>
        <div class="custom-tree-container">
          <div v-if="menus">
            <el-button @click="appendMenu" type="text" icon="el-icon-plus">新增菜单</el-button>
            <el-button @click="removeMenu" type="text" icon="el-icon-minus">删除菜单</el-button>
          </div>
          <el-tree
            :data="menus"
            node-key="id"
            accordion
            lazy
            :load="selectNode"
            :expand-on-click-node="false"
            @current-change="currentClick">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              {{data.menuName}}
            </span>
          </el-tree>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" class="menuInfo mt20">
        <el-form ref="menuInfo" :model="menuInfo" label-width="140px" v-show="isShowMenu" :rules="rules">
          <el-form-item label="菜单名称：" required prop="menuName">
            <el-input v-model="menuInfo.menuName"></el-input>
          </el-form-item>
          <template v-if="menuInfo.parentId === 0 && !menuInfo.isEditSecBtn">
            <el-form-item label="ICON：" prop="icon" required :rules="[
                { required: true, message: '请输入ICON', trigger: ['blur', 'change'] }
              ]">
              <el-input v-model="menuInfo.icon"></el-input>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="菜单URL：" prop="menuUrl" required>
              <el-input v-model="menuInfo.menuUrl"></el-input>
            </el-form-item>
          </template>
          <!-- 是否新增二级菜单 -->
          <el-form-item label="新增二级菜单：" v-if="menuInfo.parentId === 0 && !menuInfo.id && currentMenuId">
            <el-switch
              v-model="menuInfo.isEditSecBtn"
              active-color="#13ce66"
              inactive-color="#999">
            </el-switch>
          </el-form-item>
          <el-form-item label="按钮权限：" v-if="menuInfo.parentId !== 0 || menuInfo.isEditSecBtn">
            <el-tag
              v-for="tag in menuInfo.sysControl"
              :key="tag.funCode"
              closable
              :disable-transitions="false"
              class="mr10"
              @close="deleteTags(tag)">
              <a href="javascript:void(0)" @click="choseTag(tag)">{{tag.funName}}</a>
            </el-tag>
            <el-button type="text" @click="showClassify" icon="el-icon-plus" size="small" :disabled="menuInfo.parentId === 0 && !menuInfo.isEditSecBtn">新增按钮权限</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveMenu" v-if="menuInfo.id">保存</el-button>
            <el-button type="primary" @click="addMenu" v-else>新增</el-button>
            <el-button @click="cancelSave">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <Classify
      :isShowDetail.sync="isShowModel"
      @addTag="addTag"
      :dataInfo="menuInfo.sysControl"
      :menuId.sync="menuInfo.id"
      :gcode.sync="roleInfo.perCode"></Classify>
    <!-- 编辑 -->
    <EditClassify
      :isShowDetail.sync="isShowEditModel"
      @changeTag="changeTag"
      :dataDetail="chooseTagInfo"
      :dataInfo="menuInfo.sysControl"
      :menuId.sync="menuInfo.id"
      :gcode.sync="roleInfo.perCode"
      :arrayIndex="arrayIndex"></EditClassify>
  </div>
</template>

<script>
  import Classify from './components/Classify'
  import EditClassify from './components/EditClassify'
    export default {
        name: "MenuPermission",
        components: {
          Classify,
          EditClassify
        },
        data() {
          return {
            roleInfo : {
              perCode: []
            },
            roles: [],
            menus: null,
            menuInfo: {
              menuName: '',
              menuUrl: '',
              icon: '',
              parentId: 0,
              perCode: null,
              id: null,
              sysControl: [],
              isEditSecBtn: false
            },
            isShowModel: false,
            isShowMenu: false,
            isShowEditModel: false,
            rules: this.menuInfo && this.menuInfo.parentId === 0 && !this.menuInfo.isEditSecBtn ? {
              menuName: [
                { required: true, message: '请输入菜单名称', trigger: ['blur', 'change'] }
              ],
              icon: [
                { required: true, message: '请输入ICON', trigger: ['blur', 'change'] }
              ],
            } : {
              menuName: [
                { required: true, message: '请输入菜单名称', trigger: ['blur', 'change'] }
              ],
              menuUrl: [
                { required: true, message: '请输入菜单地址', trigger: ['blur', 'change'] }
              ]
            },
            // 当前选中的节点
            currentMenuId: null,
            // 当前选中的tag
            chooseTagInfo: {},
            // 编辑页面修改值相当于数组的位置
            arrayIndex: -1
          }
        },
        methods: {
          getRoles() {
            ajax.get(apis.permission.queryRoleList).then(res => {
              if(res.success) {
                this.roles = res.data
              } else {
                this.$message.error(res.message)
              }
            })
          },
          // 获取一级菜单
          getFirstMenu() {
            let data = {
              perCode: this.roleInfo.perCode[0]
            };
            ajax.post(apis.permission.queryFirstMenu, data).then(res => {
              if(res.success) {
                this.menus = res.data
              } else {
                this.$message.error(res.message)
              }
            })
          },
          // 当前节点被选中触发事件
          currentClick(data, node) {
            data.isEditSecBtn = false;
            data.sysControl = [];
            this.queryBtnPerssion(data)
          },
          // 查询按钮权限
          queryBtnPerssion(data) {
            let info = {
              menuId: data.id
            };
            this.menuInfo = {
              menuName: data.menuName,
              menuUrl: data.menuUrl,
              icon: data.icon,
              parentId: data.parentId,
              perCode: data.perCode,
              id: data.id,
              sysControl: [],
              isEditSecBtn: false
            }
            ajax.post(apis.permission.queryBtnPermission, info).then(res => {
              if(res.success) {
                this.menuInfo.sysControl = res.data;
                this.isShowMenu = true;
              } else {
                this.$message.error(res.message)
              }
            })
          },
          selectNode(node, resolve) {
            let parentInfo = node.data;
            let data = {
              parentId: parentInfo ? parentInfo.id : null,
              perCode: parentInfo ? parentInfo.perCode : ''
            };
            ajax.post(apis.permission.querySecMenu, data).then(res => {
              if(res.success) {
                // this.menus = res.data
                resolve(res.data)
              } else {
                this.$message.error(res.message)
              }
            })
          },
          // 添加按钮权限
          addTag(val) {
            this.menuInfo.sysControl.push({
              ...val
            })
          },
          changeTag(val) {
            this.arrayIndex = -1
            this.menuInfo.sysControl = val
          },
          // 新增
          addMenu() {
            let data = {
              ...this.menuInfo,
              perCode: this.roleInfo.perCode[0]
            };
            if(this.menuInfo.isEditSecBtn) {
              data.id = null
              data.parentId = this.currentMenuId
            } else {
              data.menuUrl = '';
              data.sysControl = [];
            }

            this.$refs['menuInfo'].validate((valid) => {
              if(valid) {
                ajax.post(apis.permission.addMenu, data).then(res => {
                  if(res.success) {
                    this.$message({
                      message: "成功",
                      type: "success"
                    })
                    this.getFirstMenu()
                    this.isShowMenu = false
                  } else {
                    this.$message.error(res.message)
                  }
                })
              }
            })
          },
          // 保存菜单 修改
          saveMenu() {
            // 接口 changeMenuInfo
            let data = {
              ...this.menuInfo,
              perCode: this.roleInfo.perCode[0]
            };
            if(this.menuInfo.isEditSecBtn) {
              data.id = null
              data.parentId = this.currentMenuId
            }
            this.$refs['menuInfo'].validate((valid) => {
              if(valid) {
                ajax.post(apis.permission.changeMenuInfo, data).then(res => {
                    if(res.success) {
                      this.$message({
                        message: "成功",
                        type: "success"
                      })
                      this.getFirstMenu()
                      this.isShowMenu = false
                    } else {
                      this.$message.error(res.message)
                    }
                })
              }
            })
          },
          // 重置表单
          resetForm(formName) {
            try {
              this.$refs[formName].resetFields()
            } catch (e) {
              // console.error(e)
            }
            this.menuInfo.menuUrl = ''
            this.menuInfo.sysControl = []
            // this.menuInfo.icon = ''
            this.menuInfo.id = null
            // this.menuInfo.isEditSecBtn = false
          },
          // 新增菜单
          appendMenu() {
            // this.currentClick().stop();
            if(this.menuInfo.parentId === 0) {
              this.currentMenuId =  this.menuInfo.id
            } else {
              this.currentMenuId = null
            }
            this.resetForm('menuInfo')
            this.isShowMenu = true;
          },
          // 删除菜单
          removeMenu() {
            if(!this.menuInfo.id) {
              this.$message.error("请选择要删除的菜单")
              return false;
            }
            this.$confirm('此操作将永久删除菜单, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              let data = {
                id: this.menuInfo.id
              }
              ajax.post(apis.permission.deleteMenu, data).then(res => {
                if(res.success) {
                  this.$message({
                    message: "删除菜单成功",
                    type: "success"
                  })
                  this.resetForm('menuInfo')
                  this.getFirstMenu()
                  this.isShowMenu = false;
                } else {
                  this.$message.error(res.message)
                }
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              });
            });

          },
          // 取消保存
          cancelSave() {
            this.isShowMenu = false
            this.resetForm('menuInfo')
          },
          changeRoles(vals) {
            this.isShowMenu = false;
            this.resetForm('menuInfo')
            // splice
            if(vals.length > 1) {
              this.roleInfo.perCode.splice(0, vals.length - 1)
            }
            this.getFirstMenu()
          },
          // 删除分类
          deleteTags(tag) {
            this.menuInfo.sysControl.splice(this.menuInfo.sysControl.indexOf(tag), 1)
          },
          choseTag(tag) {
            this.arrayIndex = this.menuInfo.sysControl.indexOf(tag);
            // this.menuInfo.sysControl.splice(this.menuInfo.sysControl.indexOf(tag), 1)
            this.chooseTagInfo = tag
            this.isShowEditModel  =true
          },
          // 新增分类
          showClassify() {
            this.isShowModel = true;
          },
          changeUrl(val) {
            this.menuInfo.menuUrl = val ? this.menuInfo.menuUrl : ''
          },
          changeIcon(val) {
            this.menuInfo.icon = val ? '' : this.menuInfo.icon
          }
        },
        watch: {
          'menuInfo.isEditSecBtn': function (val) {
            this.changeUrl(val)
            this.changeIcon(val)
          }
        },
        created() {
          this.getRoles()
        }
    }
</script>

<style lang="scss" scoped>
  .menuPermission {
    a {
      color: #67c23a;
    }
    .tipMessage {
      font-size: 14px;
      .tip {
        color: orangered;
      }
    }
    position: relative;
    .roles {
      position: relative;
    }
    .menuTree {
      position: relative;
    }
    .menuInfo {
      position: relative;
    }
    .lineJue {
      position: absolute;
      display: inline-block;
      left: 60%;
      top: 50%;
      width: 5rem;
      height: 2rem;
      line-height: 2rem;
      border-top-left-radius: 3px;
      border-bottom-left-radius: 3px;
      background: #90c033;
      z-index: 1000;
      &:after {
        display: inline-block;
        position: absolute;
        top: -.2rem;
        right: -2.2rem;
        content: '.';
        width: 0;
        height: 0;
        border: 1.2rem solid;
        border-color: transparent transparent transparent #CD6839;
      }
    }
  }

.menuInfo {
  .el-input {
    max-width: 300px;
  }
}

.el-tree {
  background: inherit;
}
</style>
